<template>
  <div  style="padding: 15px;">
    <vxe-toolbar id="warehouseLocationId" :custom="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="funcAdd">新增</el-button>
        <el-button @click="funcCreateBatchTask">下发</el-button>
        <el-button v-bind:disabled="printFlag" @click="funcPrint">打印盘点单</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :align="allAlign"
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      :export-config='{type:"csv"}'
      height="700"
       :loading="loading"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      sort-config.remote
      @sort-change="sortList"
      auto-resize
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="status" title="状态" min-width="140" sortable show-header-overflow show-overflow :formatter="formatterStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.status" placeholder="请选择状态" clearable>
            <el-option value="0" label="新增"/>
            <el-option value="1" label="待盘点"/>
            <el-option value="2" label="盘点中"/>
            <el-option value="3" label="待审核"/>
            <el-option value="4" label="已审核"/>
            <el-option value="5" label="作废"/>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
      <vxe-table-column field="issue" title="是否下发" min-width="150" sortable show-header-overflow show-overflow :formatter="formatterIssue"/>
      <template v-slot:header="{ column }">
        <el-select v-model="listQuery.issue" placeholder="请选择" clearable>
          <el-option
            v-for="item in issueList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </template>
    </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="code" title="盘点单号" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.code" placeholder="请输入盘点单号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="type" title="单据类型" min-width="150" sortable :formatter="formatterType"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.type" placeholder="请选择单据类型" clearable>
            <el-option value="0" label="全盘"/>
            <el-option value="1" label="入驻商盘点"/>
            <el-option value="2" label="库位盘点"/>
            <el-option value="3" label="动碰盘点"/>
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="warehouseCode" title="仓库" min-width="150" sortable :formatter="formatterWarehouse"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请输入所属仓库 " style="width:100%" clearable>
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="supervisor" title="监盘人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.supervisor" placeholder="请输入监盘人" clearable />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="createdName" title="创建人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.createdName" placeholder="请输入创建人" clearable />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          show-header-overflow
          show-overflow
          title="创建时间"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="modifiedName" title="修改人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.modifiedName" placeholder="请输入修改人" clearable />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="gmtModified"
          show-header-overflow
          show-overflow
          title="修改时间"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>

      <vxe-table-column title="操作" fixed="right" min-width="170">
        <template slot-scope="scope">
           <el-tooltip  effect="dark" content="查看" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code,scope.row.status)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip v-if="scope.row.status == '0'"  effect="dark" content="修改" placement="top">
            <vxe-button type="text" @click="funcEdit(scope.row.code)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip v-if="scope.row.status == '0'"  effect="dark" content="作废" placement="top">
            <vxe-button type="text" @click="funcInvalid(scope.row.code)">
              <i class="el-icon-document-delete" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="下发" placement="top" v-if="(scope.row.status == '1') && scope.row.issue == '0'">
            <vxe-button type="text" @click="funcCreateTask(scope.row.code)">
              <i class="el-icon-s-promotion" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip v-if="scope.row.status == '1' || scope.row.status == '2'"  effect="dark" content="盘点登记" placement="top">
            <vxe-button type="text" @click="funcRegister(scope.row.code)">
              <i class="el-icon-receiving" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
<!--     <vxe-modal v-model="modelAddFlag" title="新增" width="1200" height="900" resize>-->
<!--      <compAdd ref="addRef" @fatherAddMethod="fatherAdd" @fatherCancelMethod="fatherCancel" />-->
<!--    </vxe-modal>-->
    <!--<vxe-modal v-model="modelRegisterFlag" title="盘点登记" width="1200" height="900" resize>
      <compRegister ref="registerRef" @fatherRegisterMethod="fatherRegister" @fatherCancelMethod="fatherCancel" />
    </vxe-modal>-->
    <vxe-modal v-model="modelPrintFlag" title="打印" width="900" height="800" resize>
      <compPrint ref="printRef" @fatherPrintMethod="fatherPrint"/>
    </vxe-modal>

  </div>
</template>
<script>
  import 'xe-utils'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  // import compAdd from './components/countingAdd.vue'
  // import compEdit from './components/countingEdit.vue'
  import compPrint from './components/print.vue'

  // import compDetail from './components/countingDetail.vue'
  import { createTask, createBatchTask } from '@/api/store'
  import { getWarehouse } from '@/api/basicInfo'
  import { countingDelete, countingInvalid, countingList } from '@/api/store'

  export default {
  name: '盘点管理',
  components: {
    // compAdd,
    // compEdit,
    // compRegister,
    compPrint,
    // compDetail,
  },
  data() {
    return {
      message: '',
      // 日期选项
      // 日期选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      warehouseData:[],
      loading: false,
      allAlign: 'center',
      tableData: [],
      modelAddFlag: false,
      initFinishFlag: false,
      modelEditFlag: false,
      modelPrintFlag:false, //打印开关

      modelRegisterFlag: false,
      modelDetailFlag: false,
      gmtCreatedRange:"",
      gmtModifiedRange:"",
      copy: false,
      listQuery: {
        total: 0,             //总数
        createdBy:'',         //创建人
        createdName:'',         //创建人
        modifiedBy:'',        //修改人
        modifiedName:'',        //修改人
        code:'',                                                //拣货单号 ,
        notPickingQuantity:'',                                  //待拣数量 ,
        pickingQuantity:'',                                     //拣货数量 ,
        planQuantity:'',                                        //计划数量 ,
        remarks:'',                                             //备注 ,
        shipmentCode:'',                                        //入驻商 ,
        sourceCode:'',                                          //来源单号 ,
        status:'',                                              //状态 ,
        type:'',                                                //单据类型 ,
        warehouseCode:'',                                       //仓库
        pageNum: 1,
        pageSize: 10,
        sortField: '',
        sortType: ''
      },
      issueList: [
        {code: '0', name:'否'},
        {code: '1', name:'是'},
      ],
    }
  },
  mounted() {
    this.getWarehouses()
    this.$eventBus.$on("refreshList", () => {
      this.findList()
    })
  },
  methods: {
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    funcInvalid(row) {
      this.$confirm('确认作废吗？').then(_ => {
        countingInvalid(row).then(response => {
          this.$message({ message: response.msg, type: 'success' })
          this.findList();
        })
      }).catch(_ => {})
    },
    getWarehouses(){
      getWarehouse().then(response => {
        this.warehouseData = response.data;
        this.findList();

        this.initFinishFlag = true;
      })
    },
    // 翻译仓库
    formatterWarehouse({ cellValue }) {
      const sd = this.warehouseData.find(i => i.code === cellValue)
      return sd ? sd.name : ''
    },
    // 翻译状态
    formatterStatus({ cellValue }) {
      if (cellValue === '0') {
        return '新增'
      } else if (cellValue === '1') {
        return '待盘点'
      } else if(cellValue === '2') {
        return '盘点中'
      } else if(cellValue === '3') {
        return '待审核'
      } else if(cellValue === '4') {
        return '已审核'
      } else if(cellValue === '5') {
        return '作废'
      }
    },
    // 打印组件的父方法
    fatherPrint() {
      this.modelPrintFlag = false
      this.findList()
    },

    //翻译单据类型
    formatterType({ cellValue }) {
      if (cellValue === '0') {
        return '全盘'
      } else if (cellValue === '1') {
        return '入驻商盘点'
      } else if(cellValue === '2') {
        return '库位盘点'
      } else if(cellValue === '3') {
        return '动碰盘点'
      }
    },
    //获取列表
    findList() {
      this.loading = true
      return countingList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.listQuery.total = response.data.total
        this.loading = false
      })
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property
        this.listQuery.sortType = order
      } else {
        this.listQuery.sortField = ''
      }
      this.findList()
    },
    // 添加方法
    funcAdd() {
      this.$router.push({
        path: "/kngl/countingAdd",
      });
    },
    // 编辑
    funcEdit(code) {
      this.$router.push({
        path: "/kngl/countingEdit",
        query: { code: code,}
      });
    },
    // 盘点登记方法
    funcRegister(code) {
      this.$router.push({
        path: "/kngl/countingRegister",
        query: { code: code,}
      });
    },
    // 详情方法
    funcDetail(code,status) {
      this.$router.push({
        path: "/kngl/countingDetail",
        query: { code: code,status:status}
      });
    },
    // 删除方法
    funcDelete(row) {
      this.$confirm('确认删除吗？').then(_ => {
        countingDelete(row).then(response => {
          this.$message({ message: response.msg, type: 'success' })
          this.findList()
        })
      }).catch(_ => {})
    },
    // 增加组件的父方法
    fatherAdd() {
      this.modelAddFlag = false
      this.findList()
    },
    // 编辑组件的父方法
    fatherEdit() {
      this.modelEditFlag = false
      this.findList()
    },
    // 盘点登记组件的父方法
    fatherRegister() {
      this.modelRegisterFlag = false;
      this.findList();
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case 'add':
          this.modelAddFlag = false
          break
        case 'edit':
          this.modelEditFlag = false
          break
        case 'detail':
          this.modelDetailFlag = false
          break
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage
      this.listQuery.pageSize = pageSize
      this.findList()
    },
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['pageviews', 'forecast'].includes(column.property)) {
            return XEUtils.sum(data, column.property)
          }
          return null
        })
      ]
    },
    //打印
    funcPrint() {
      let nowDate = new Date();
      let year = nowDate.getFullYear()
      let month = nowDate.getMonth() + 1
      let date = nowDate.getDate()
      let hh =new Date(nowDate).getHours() < 10? "0" + new Date(nowDate).getHours(): new Date(nowDate).getHours();
      let mm =new Date(nowDate).getMinutes() < 10? "0" + new Date(nowDate).getMinutes(): new Date(nowDate).getMinutes();
      let ss =new Date(nowDate).getSeconds() < 10? "0" + new Date(nowDate).getSeconds(): new Date(nowDate).getSeconds();

      if (month >= 1 && month <= 9) {
        month = "0" + month
      }
      if (date >= 0 && date <= 9) {
        date = "0" + date
      }
      let systemDate = year + '-' + month + '-' + date +" "+ hh + ":" + mm + ':' + ss ;
      this.$refs.printRef.date = systemDate
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      let arr = []
      selectRecords.forEach( i => {
        arr.push(i.code)
      })
      this.$refs.printRef.getInfo(arr)
      this.modelPrintFlag = true
    },

    // 批量下发
    funcCreateBatchTask(){
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.code)
        })
        let params = {
          taskType: 'INVENTORY',
          sourceCodes: arr
        }
        if (arr.length != 0) {
          this.$confirm('确认下发吗？').then(_ => {
            this.loading = true
            createBatchTask(params).then((response)=>{
              this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
              this.findList()
              this.loading = false

            })
          })
        } else {
          this.$message('请选择要下发的单据')
        }
    },

    // 单个下发
    funcCreateTask(code){
      let params = {
        taskType: 'INVENTORY',
        sourceCode: code
      }
      this.$confirm('确认下发吗？').then(_ => {
        this.loading = true
        createTask(params).then((response)=>{
          this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
          this.findList()
          this.loading = false

        })
      })
    },
    formatterIssue({cellValue}){
      if(cellValue == '0'){
        return '否'
      }else if(cellValue == '1'){
        return  '是'
      }
      return cellValue
    },

  },
  computed: {
    'printFlag': function() {
      if(this.initFinishFlag) {
        let selectRecords = this.$refs.xTable.getCheckboxRecords();
        if(selectRecords.length > 0) {
          return false;
        } else {
          return true;
        }
      }
      return true;
    }
  },
  destroyed() {
    this.$eventBus.$off('refreshList')
  },
}
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
